//
//  JGMapViewController.m
//  JGMeiTuanHD
//
//  Created by JJetGu on 15/10/3.
//  Copyright (c) 2015年 Free. All rights reserved.
//

#import "JGMapViewController.h"
#import <MapKit/MapKit.h>
#import "UIBarButtonItem+Extension.h"
#import "DPAPI.h"
#import "JGBusiness.h"
#import "JGDeal.h"
#import "MJExtension.h"
#import "JGMetaTool.h"
#import "JGCategory.h"
#import "JGHomeTopItem.h"
#import "JGCategoryViewController.h"
#import "JGConst.h"
#import "JGDealAnnotation.h"
#import "JGBusiness.h"
#import "JGDPRequestTool.h"
#import "JGDealAnnoRightButton.h"
#import "MBProgressHUD+MJ.h"
#import "JGDetailViewController.h"

@interface JGMapViewController () <MKMapViewDelegate>

@property(nonatomic,strong) CLLocationManager *locMgr;

@property (weak, nonatomic) IBOutlet MKMapView *mapView;
/** 反地理编码获得地理位置*/
@property (nonatomic ,strong) CLGeocoder *coder;
@property (nonatomic, copy) NSString *city;
/**
 *  是否正在处理团购信息（是否在请求中）
 */
@property (nonatomic, assign, getter = isDealingDeals) BOOL dealingDeals;

/** 当前选中的分类 */
@property (strong, nonatomic) JGCategory *selectedCategory;
/** 分类item */
@property (nonatomic, weak) UIBarButtonItem *categoryItem;
/** 分类popover */
@property (nonatomic, strong) UIPopoverController *categoryPopover;

@property (nonatomic, copy) NSString *selectedCategoryName;

@end

@implementation JGMapViewController

- (void)dealloc
{
    [JGNotificationCenter removeObserver:self];
}

- (CLGeocoder *)coder
{
    if (!_coder) {
        self.coder = [[CLGeocoder alloc] init];
    }
    return _coder;
}

-(CLLocationManager *)locMgr{
    if (_locMgr==nil) {
        _locMgr=[[CLLocationManager alloc]init];
    }
    return _locMgr;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // 设置导航栏的内容
    [self setupNav];
    
    // 设置地图
    [self setupMap];
    
    // 监听分类改变
    [JGNotificationCenter addObserver:self selector:@selector(categoryDidChange:) name:JGCategoryDidChangeNotification object:nil];
}

/**
 *  设置导航栏的内容
 */
- (void)setupNav
{
    // 左边的返回
    UIBarButtonItem *backItem = [UIBarButtonItem itemWithTarget:self action:@selector(back) image:@"icon_back" highImage:@"icon_back_highlighted"];
    // 设置左上角的分类菜单
    JGHomeTopItem *categoryTopItem = [JGHomeTopItem item];
    [categoryTopItem addTarget:self action:@selector(categoryClick)];
    [categoryTopItem setIcon:@"btn_changeCity" highIcon:@"btn_changeCity_selected"];
    [categoryTopItem setTitle:@"美团"];
    [categoryTopItem setSubtitle:@"全部分类"];
    UIBarButtonItem *categoryItem = [[UIBarButtonItem alloc] initWithCustomView:categoryTopItem];
    self.categoryItem = categoryItem;
    
    self.navigationItem.leftBarButtonItems = @[backItem, categoryItem];
    
    // 标题
    self.title = @"地图";
}

/**
 *  设置地图
 */
- (void)setupMap
{
    self.mapView.delegate = self;
    // 设置地图跟踪用户的位置
    self.mapView.userTrackingMode = MKUserTrackingModeFollow;
    
    if ([[UIDevice currentDevice].systemVersion doubleValue]>=8.0) {
        [self.locMgr requestWhenInUseAuthorization];
    }
}

#pragma mark - 导航栏左边处理
/** 分类菜单 */
- (void)categoryClick
{
    // 显示分类菜单
    self.categoryPopover = [[UIPopoverController alloc] initWithContentViewController:[[JGCategoryViewController alloc] init]];
    [self.categoryPopover presentPopoverFromBarButtonItem:self.categoryItem permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

#pragma mark - 通知监听方法
/** 分类选择结果通知 */
- (void)categoryDidChange:(NSNotification *)notification
{
    // 1.关闭popover
    [self.categoryPopover dismissPopoverAnimated:YES];
    
    // 2.获得要发送给服务器的类型名称
    JGCategory *category = notification.userInfo[JGSelectCategory];
    self.selectedCategory = category;
    NSString *subcategoryName = notification.userInfo[JGSelectSubcategoryName];
    if (subcategoryName == nil || [subcategoryName isEqualToString:@"全部"]) { // 点击的数据没有子分类
        self.selectedCategoryName = category.name;
    } else {
        self.selectedCategoryName = subcategoryName;
    }
    if ([self.selectedCategoryName isEqualToString:@"全部分类"]) {
        self.selectedCategoryName = nil;
    }
    
    NSLog(@"选择的分类：：：%@", self.selectedCategoryName);
    
    // 3.删除之前的所有大头针
    [self.mapView removeAnnotations:self.mapView.annotations];
    
    // 4.重新发送请求给服务器 --- 调用他的代理方法
    [self mapView:self.mapView regionDidChangeAnimated:YES];
    
     // 5.更换顶部item的文字
    JGHomeTopItem *topItem = (JGHomeTopItem *)self.categoryItem.customView;
    [topItem setIcon:category.icon highIcon:category.highlighted_icon];
    [topItem setTitle:category.name];
    [topItem setSubtitle:subcategoryName];
}

- (void)back {
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - 返回用户原来的位置
- (IBAction)returnOriginLocation:(UIButton *)sender {
    [self.mapView setCenterCoordinate:self.mapView.userLocation.location.coordinate animated:YES];
}


#pragma mark - MKMapViewDelegate
/**
 * 当用户的位置更新了就会调用一次
 */
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
     // 让地图显示到用户所在的位置
    MKCoordinateRegion region = MKCoordinateRegionMake(userLocation.location.coordinate, MKCoordinateSpanMake(0.25,0.25));
    [mapView setRegion:region animated:YES];
    
    
    // 经纬度 --> 城市名 : 反地理编码
    // 城市名 --> 经纬度 : 地理编码
    // 获得城市名称
    [self.coder reverseGeocodeLocation:userLocation.location completionHandler:^(NSArray *placemarks, NSError *error)
    {
        if (error || placemarks.count == 0) return;
        
        CLPlacemark *pm = [placemarks firstObject];
//        NSLog(@"位置信息：%@", pm);
        NSString *cityName = pm.locality ? pm.locality : pm.addressDictionary[@"State"];
        //大众点评的特殊要求，去掉名字后面的市
        self.city = [cityName substringToIndex:cityName.length - 1];
        NSLog(@"定位到的城市名称：%@", self.city);
        
        // 定位到城市，就发送请求
        [self mapView:self.mapView regionDidChangeAnimated:YES];
    }];
}

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
     if (self.city == nil || self.isDealingDeals) return;
    
    self.dealingDeals = YES;
    
    // 发送请求给服务器
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    //城市
    params[@"city"] = self.city;
    //类别
    if (self.selectedCategoryName) {
        params[@"category"] = self.selectedCategoryName;
    }
    // 经纬度(设置位置信息)
    params[@"latitude"] = @(mapView.region.center.latitude);
    params[@"longitude"] = @(mapView.region.center.longitude);
    params[@"radius"] = @(5000);
    
    __weak typeof(self) weakSelf = self;
    [[JGDPRequestTool sharedAPITool] request:@"v1/deal/find_deals" params:params success:^(id json) {
        
        NSArray *deals = [JGDeal objectArrayWithKeyValuesArray:json[@"deals"]];
        [self setupDeals:deals];
        
    } failure:^(NSError *error) {
        NSLog(@"请求失败 - %@", error);
        [MBProgressHUD showError:@"网络繁忙,请稍后再试" toView:weakSelf.view];
        weakSelf.dealingDeals = NO;
    }];
}

/**
 *  处理请求下来的团购数据  _多线程的解析： http://blog.sina.com.cn/s/blog_b22973cf01019ixl.html
 */
- (void)setupDeals:(NSArray *)deals
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
        for (JGDeal *deal in deals) {
            // 获得团购所属的类型
//            JGCategory *category = [JGMetaTool categoryWithDeal:deal];
            for (JGBusiness *business in deal.businesses) {
                //给打头针模型赋值
                JGDealAnnotation *anno = [[JGDealAnnotation alloc] init];
                anno.coordinate = CLLocationCoordinate2DMake(business.latitude, business.longitude);
                anno.title = business.name;
                anno.subtitle = deal.title;
                // 设置大头针对应的团购模型
                anno.deal = deal;
                
                //若包含有之前的相同位置的大头针
                if ([self.mapView.annotations containsObject:anno]) break;
                
                dispatch_sync(dispatch_get_main_queue(), ^{
                    [self.mapView addAnnotation:anno];
                });
            }
        }
        self.dealingDeals = NO;
    });
}

/**
 * 处理大头针的样式
 */
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(JGDealAnnotation *)annotation
{
    // 返回nil,意味着交给系统处理 --- 比如用户的当前位置图标
    if (![annotation isKindOfClass:[JGDealAnnotation class]]) return nil;
    
    // 创建自定义的大头针控件
    static NSString *ID = @"deal";
    JGDealAnnoRightButton *rightBtn = nil;
    MKAnnotationView *annoView = [mapView dequeueReusableAnnotationViewWithIdentifier:ID];
    if (annoView == nil) {
        annoView = [[MKAnnotationView alloc] initWithAnnotation:nil reuseIdentifier:ID];
        // 显示标题和标题
        annoView.canShowCallout = YES;
        rightBtn = [JGDealAnnoRightButton buttonWithType:UIButtonTypeDetailDisclosure];
        [rightBtn addTarget:self action:@selector(dealClick:) forControlEvents:UIControlEventTouchUpInside];
        annoView.rightCalloutAccessoryView = rightBtn;
    } else { // annoView是从缓存池取出来
        rightBtn = (JGDealAnnoRightButton *)annoView.rightCalloutAccessoryView;
    }
    
    // 设置模型(位置\标题\子标题)
    annoView.annotation = annotation;
    // 设置图标
    if (self.selectedCategoryName == nil) { //全部分类
        NSString *category = [annotation.deal.categories firstObject];
        NSString *mapIcon = [JGMetaTool categoryWithName:category].map_icon;
//        if (mapIcon == nil) {
//            mapIcon =@"ic_category_78";
//        }
        annoView.image = [UIImage imageNamed:mapIcon];
    } else { //特定
        annoView.image = [UIImage imageNamed:self.selectedCategory.map_icon];
    }
    
    rightBtn.deal = annotation.deal;
    
    return annoView;
}

- (void)dealClick:(JGDealAnnoRightButton *)btn
{
    // 弹出详情控制器
    JGDetailViewController *detailVc = [[JGDetailViewController alloc] init];
    detailVc.deal = btn.deal;
    [self presentViewController:detailVc animated:YES completion:nil];
}

@end
